package com.yougou.ui.category;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.yougou.base.BaseViewModel;
import com.yougou.data.model.Category;
import com.yougou.data.model.Goods;
import com.yougou.data.repository.CategoryRepository;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class CategoryViewModel extends BaseViewModel {
    
    private final CategoryRepository mRepository;
    private final MutableLiveData<List<Category>> mCategoryList = new MutableLiveData<>();
    private final MutableLiveData<List<Goods>> mGoodsList = new MutableLiveData<>();
    private final MutableLiveData<Boolean> mLoading = new MutableLiveData<>(false);
    private final MutableLiveData<String> mError = new MutableLiveData<>();
    
    private List<Goods> mAllGoods = new ArrayList<>();
    private Category mCurrentCategory;
    
    public CategoryViewModel() {
        mRepository = new CategoryRepository();
    }
    
    public LiveData<List<Category>> getCategoryList() {
        return mCategoryList;
    }
    
    public LiveData<List<Goods>> getGoodsList() {
        return mGoodsList;
    }
    
    public LiveData<Boolean> isLoading() {
        return mLoading;
    }
    
    public LiveData<String> getError() {
        return mError;
    }
    
    
    public void loadCategories() {
        mLoading.setValue(true);
        addDisposable(
            mRepository.getCategories()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    response -> {
                        mLoading.setValue(false);
                        if (response.isSuccess() && response.getMessage() != null) {
                            mCategoryList.setValue(response.getMessage());
                        } else {
                            mError.setValue("获取分类失败");
                        }
                    },
                    error -> {
                        mLoading.setValue(false);
                        mError.setValue("网络错误: " + error.getMessage());
                    }
                )
        );
    }
    
    
    public void loadGoodsByCategory(int categoryId) {
        addDisposable(
            mRepository.searchGoodsByCategory(categoryId, 1, 20)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    response -> {
                        if (response.isSuccess() && response.getMessage() != null) {
                            mGoodsList.setValue(response.getMessage().getGoods());
                        }
                    },
                    error -> {
                        mError.setValue("加载商品失败: " + error.getMessage());
                    }
                )
        );
    }
    
    
    public void loadAllGoods() {
        addDisposable(
            mRepository.searchGoodsByCategory(0, 1, 100)  // 加载更多商品用于过滤
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    response -> {
                        if (response.isSuccess() && response.getMessage() != null) {
                            mAllGoods = response.getMessage().getGoods();
                            // 如果有缓存的分类，自动过滤
                            if (mCurrentCategory != null) {
                                filterGoodsByCategory(mCurrentCategory);
                            } else {
                                mGoodsList.setValue(mAllGoods);
                            }
                        }
                    },
                    error -> {
                        mError.setValue("加载商品失败: " + error.getMessage());
                    }
                )
        );
    }
    
    
    public void filterGoodsByCategory(Category category) {
        // 缓存当前分类
        mCurrentCategory = category;
        
        int categoryId = category.getCatId();

        mLoading.setValue(true);
        addDisposable(
            mRepository.searchGoodsByCategory(categoryId, 1, 50)  // 每页50个商品
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    response -> {
                        mLoading.setValue(false);
                        if (response.isSuccess() && response.getMessage() != null) {
                            List<Goods> goods = response.getMessage().getGoods();
                            if (goods != null) {
                                mGoodsList.setValue(goods);
                            } else {
                                mGoodsList.setValue(new ArrayList<>());
                            }
                        } else {
                            mGoodsList.setValue(new ArrayList<>());
                        }
                    },
                    error -> {
                        mLoading.setValue(false);
                        mError.setValue("加载商品失败: " + error.getMessage());
                        mGoodsList.setValue(new ArrayList<>());
                    }
                )
        );
    }
    
    
    public void filterGoodsByCategoryId(int categoryId) {
        if (mAllGoods.isEmpty()) {
            loadAllGoods();
            return;
        }
        
        List<Goods> filteredGoods = new ArrayList<>();
        for (Goods goods : mAllGoods) {
            if (goods.getCatId() == categoryId || 
                goods.getCatOneId() == categoryId || 
                goods.getCatTwoId() == categoryId || 
                goods.getCatThreeId() == categoryId) {
                filteredGoods.add(goods);
            }
        }
        
        // 显示过滤后的商品列表
        mGoodsList.setValue(filteredGoods);
    }
    
    
    public void filterGoodsByCategoryName(String categoryName) {
        if (mAllGoods.isEmpty()) {
            loadAllGoods();
            return;
        }
        
        List<Goods> filteredGoods = new ArrayList<>();
        for (Goods goods : mAllGoods) {
            // 如果商品名称包含分类名称，也算匹配
            if (goods.getGoodsName().contains(categoryName)) {
                filteredGoods.add(goods);
            }
        }
        
        // 显示过滤后的商品列表
        mGoodsList.setValue(filteredGoods);
    }
}

